package com.colombounplug.gwtmini.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ButtonBase;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 * @author anuradha.uduwage
 */
public class GWTMini implements EntryPoint {

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		RootPanel.get().add(getDiggStoriesButton());
	}
	
	/**
	 * Create a button that has action to connect to digg api.
	 * @return
	 */
	private ButtonBase getDiggStoriesButton() {
		Button diggButton = new Button("Digg It", new ClickHandler() {
			public void onClick(ClickEvent event) {
				renderJson();
			}
		});
		diggButton.setStyleName("sendButton");
			
		return diggButton;
	} 
	
	/**
	 * Method request JSONP data by adding the default callback method to url. It also extract jsonp data
	 * based on onSuccess and returns an error message onFailure. 
	 */
	public void renderJson() {

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
		String url = "http://services.digg.com/2.0/story.getTopNews?type=javascript";
		
		jsonp.requestObject(url, new AsyncCallback<DiggStoryHolder>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Failure:" + caught.getMessage());
			}

			@Override
			public void onSuccess(DiggStoryHolder result) {
				VerticalPanel vp = new VerticalPanel();
				FlexTable diggTable = new FlexTable();
				diggTable.setStyleName("diggTableStyle");
				diggTable.setCellPadding(5);
				diggTable.setWidth("100%");
				int row;

				if (result.getStoryInfo() != null) {
					for (int count = 0; count < result.getStoryInfo().length(); count++) {
						//get the total story count returned by the jsonp
						DiggStoryCountEntry entry = result.getStoryInfo().get(count);
						//adding to the panels.
						HorizontalPanel hp = new HorizontalPanel();
						hp.setSpacing(10);
						hp.add(new Label(entry.getStoryTitle()));
						//converting string to match JSNI return data type.
						Integer diggCount = entry.getDiggs();
						hp.add(new Label(diggCount.toString()));
						vp.add(hp);
						row = diggTable.getRowCount();
						
						diggTable.setText(row + 1, 1, entry.getStoryTitle());
						diggTable.setText(row + 1, 2, diggCount.toString());
					}
				}
				RootPanel.get().add(diggTable);
			}
		});
	}
}
